import mysql.connector
import os
from config import DB_CONFIG

def create_database():
    try:
        # 连接到MySQL服务器
        print("正在连接到MySQL服务器...")
        conn = mysql.connector.connect(
            host=DB_CONFIG['host'],
            user=DB_CONFIG['user'],
            password=DB_CONFIG['password']
        )
        cursor = conn.cursor()

        # 读取schema.sql文件
        print("正在读取schema.sql文件...")
        # 动态处理schema.sql文件路径
        schema_path = os.path.join(os.path.dirname(__file__), 'schema.sql')
        # 在原有执行逻辑中增加DELIMITER处理
        with open(schema_path, 'r', encoding='utf-8') as file:
            # 替换存储过程的分号
            sql_commands = file.read().replace('END$$', 'END;;')
            commands = [cmd.strip() for cmd in sql_commands.split(';;') if cmd.strip()]
            
        for command in commands:
            print(f"执行SQL: {command[:100]}...")
            cursor.execute(command, multi=True)
            conn.commit()

        print("数据库和表创建成功！")
        cursor.close()
        conn.close()

    except mysql.connector.Error as err:
        print(f"MySQL错误: {err}")
        if err.errno == 1045:  # 访问被拒绝
            print("请检查用户名和密码是否正确")
        elif err.errno == 1049:  # 数据库不存在
            print("请确保数据库已创建")
        elif err.errno == 1146:  # 表不存在
            print("请确保表结构正确")
    except FileNotFoundError:
        print("找不到schema.sql文件，请确保文件存在")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    create_database()